import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { DatePipe } from '@angular/common';

import { timeForMat } from 'src/app/comm';
import { CustomerIdolStatisticsService } from './customer-idol-statistics.service';
import { CommonService } from 'src/app/services-common/common.service';

@Component({
  selector: 'app-customer-idol-statistics',
  templateUrl: './customer-idol-statistics.component.html',
  styleUrls: ['./customer-idol-statistics.component.scss'],
  providers: [DatePipe]
})
export class CustomerIdolStatisticsComponent implements OnInit, AfterViewInit {
  @ViewChild('incomeLineRef') incomeLineRef: any;
  @ViewChild('outLineRef') outLineRef: any;

  cardSize: any = 'small';
  /**
   * ----------------------------------------------------------------
   * 统计 TOP
   * ----------------------------------------------------------------
   */
  topLoading: boolean = false;
  rangeTypes = [
    { value: 1, label: '昨日' },
    { value: 7, label: '近7天' },
    { value: 30, label: '近30天' },
    { value: 90, label: '近90天' }
  ];
  ranges: any = {};
  dateArrs: any = [];
  sensusParams: any = {
    beginTime: '',
    endTime: ''
  }
  censusTopData: any = {};

  /**
   * ----------------------------------------------------------------
   * 统计 Charts
   * ----------------------------------------------------------------
   */
  chartsLoading: boolean = false;
  rangeChartTypes = [
    { value: 7, label: '近7天' },
    { value: 30, label: '近30天' },
    { value: 90, label: '近90天' }
  ];
  chartRanges: any = {};
  chartDateArrs: any = [];
  chartParams: any = {
    beginTime: '',
    endTime: ''
  }

  // 收入chart
  incomeChartList: any = {
    'adz': '定制分成',
    'redPacket': '红包分成',
    'alw': '爱乐物-推广分成',
    'aisi': '爱思助手-推广分成',
    'gameDivide': '游戏-推广分成',
    'aiSiRecovery': '爱思回收-推广分成',
    'secondOrderReturn': '二手订单退还',
    'activity': '活动奖励',
    'drawingReturn': '图纸会员退还',
    'rechargeReturn': '充值专区退还',
    'adzReturn': '定制订单退还',
    'orderReturn': '配件订单退还',
    'redPacketReturn': '红包退还',
    'idol': '购买爱豆',
    'recoveryDeal': '回收成交'
  };
  incomeChartConfig: any = {
    legendData: [],
    xAxisData: [],
    seriesData: []
  }
  // 支出chart
  expendChartList: any = {
    'game': '游戏消费',
    'test': '验机消费',
    'jd': '兑换京东卡',
    'secondOrderConsume': '二手订单消费',
    'orderConsume': '配件订单消费',
    'adzConsume': '定制订单消费',
    'redPacketConsume': '红包消费',
    'drawingConsume': '图纸会员消费',
    'rechargeConsume': '充值专区消费'
  };
  expendChartConfig: any = {
    legendData: [],
    xAxisData: [],
    seriesData: []
  }

  /**
   * ----------------------------------------------------------------
   * Table Modal
   * ----------------------------------------------------------------
   */
  modalTableParams = {
    page: 1,
    pageSize: 20,
    total: 0
  }

  // 收入 Modal
  isIncomeVisible = false;
  incomeTableData: any = [];

  // 支出 Modal
  isExpendVisible = false;
  expendTableData: any = []

  constructor(
    private message: NzMessageService,
    private datePipe: DatePipe,
    private services: CustomerIdolStatisticsService,
    private commonService: CommonService
  ) {
    // 统计：日期选择快捷设置
    this.rangeTypes.forEach((item: any) => {
      this.ranges[item.label] = [...this.timeRangesFilter(item.value)];
    })
    // charts：日期选择快捷设置
    this.rangeChartTypes.forEach((item: any) => {
      this.chartRanges[item.label] = [...this.timeRangesFilter(item.value)];
    })
  }

  ngOnInit(): void {
    // 统计默认近七日
    this.dateArrs = this.timeRangesFilter(7);
    this.sensusParams.beginTime = this.datePipe.transform(this.dateArrs[0], 'yyyy-MM-dd');
    this.sensusParams.endTime = this.datePipe.transform(this.dateArrs[1], 'yyyy-MM-dd');
    this.getTopCensusData();

    // charts默认近三十日
    this.chartDateArrs = this.timeRangesFilter(30);
    this.chartParams.beginTime = this.datePipe.transform(this.chartDateArrs[0], 'yyyy-MM-dd');
    this.chartParams.endTime = this.datePipe.transform(this.chartDateArrs[1], 'yyyy-MM-dd');
    this.getChartTaleData();
  }

  ngAfterViewInit(): void {
  }

  // 查询统计TOP
  async getTopCensusData() {
    let params = {
      ...this.sensusParams
    }
    this.topLoading = true;
    const res: any = await this.services.idolStatisticsData(params);
    this.topLoading = false;
    
    if (res.code == 0) {
      this.censusTopData = res.data || {};
    } else {
      this.message.error(res.message);
    }
  }

  // 查询charts
  async getChartTaleData() {
    let params = {
      ...this.chartParams
    }
    this.chartsLoading = true;
    const res: any = await this.services.getchartTableData(params);
    this.chartsLoading = false;

    if (res.code == 0) {
      const { incomeCensusList, expendCensusList } = res.data || {};

      // 收入Table | Chart
      this.incomeTableData = incomeCensusList?.length ? JSON.parse(JSON.stringify(incomeCensusList)).reverse() : [];
      this.incomeChartConfig.legendData = Object.values(this.incomeChartList);
      this.incomeChartConfig.xAxisData = incomeCensusList.map((item: any) => item.DAY_SHORT_DESC);
      this.incomeChartConfig.seriesData = [];
      Object.keys(this.incomeChartList).forEach((key: any) => {
        this.incomeChartConfig.seriesData.push({
          name: this.incomeChartList[key],
          type: 'line',
          smooth: true,
          data: incomeCensusList.map((ele: any) => ele[key] || 0)
        })
      })
      setTimeout(() => {
        this.incomeLineRef.initCharts();
      })

      // 支出Table | Chart
      this.expendTableData = expendCensusList?.length ? JSON.parse(JSON.stringify(expendCensusList)).reverse() : [];
      this.expendChartConfig.legendData = Object.values(this.expendChartList);
      this.expendChartConfig.xAxisData = expendCensusList.map((item: any) => item.DAY_SHORT_DESC);
      this.expendChartConfig.seriesData = [];
      Object.keys(this.expendChartList).forEach((key: any) => {
        this.expendChartConfig.seriesData.push({
          name: this.expendChartList[key],
          type: 'line',
          smooth: true,
          data: expendCensusList.map((ele: any) => ele[key])
        })
      })
      setTimeout(() => {
        this.outLineRef.initCharts();
      })
    } else {
      this.message.error(res.message);
    }
  }

  dateChange(result: Date[], num: number): void {
    let stime = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd') : '';
    let etime = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd') : '';
    if (num == 0) {
      this.sensusParams.beginTime = stime;
      this.sensusParams.endTime = etime;
    } else {
      this.chartParams.beginTime = stime;
      this.chartParams.endTime = etime;
    }
  }

  /**
   * 搜索 | 重置 num: 0、统计，1、charts
   * ----------------------------------------------------------------
   */
  seachData(num: number) {
    if (num == 0) {
      this.getTopCensusData();
    } else {
      this.getChartTaleData();
    }
  }
  resetData(num: number) {
    if (num == 0) {
      // 统计默认近七日
      this.dateArrs = this.timeRangesFilter(7);
      this.sensusParams.beginTime = this.datePipe.transform(this.dateArrs[0], 'yyyy-MM-dd');
      this.sensusParams.endTime = this.datePipe.transform(this.dateArrs[1], 'yyyy-MM-dd');

      this.getTopCensusData();
    } else {
      // charts默认近三十日
      this.chartDateArrs = this.timeRangesFilter(30);
      this.chartParams.beginTime = this.datePipe.transform(this.chartDateArrs[0], 'yyyy-MM-dd');
      this.chartParams.endTime = this.datePipe.transform(this.chartDateArrs[1], 'yyyy-MM-dd');

      this.getChartTaleData();
    }
  }

  handleCancel() {
    this.isIncomeVisible = false;
    this.isExpendVisible = false;
  }

  // 日期选择快捷设置
  timeRangesFilter(num: number) {
    const { stime, etime } = timeForMat(num);
    return [new Date(stime), new Date(etime)];
  }

  // TOP百分比filter
  percentageFilter(num: number) {
    let tmpStr = '0%';
    if (num && num > 0) {
      tmpStr = (num * 100).toFixed(2) + '%';
    }
    return tmpStr;
  }

  /**
   * 导出
   * @param num 0：收入，1：支出
   */
  async exportTable(num: number) {
    let params = {
      ...this.chartParams
    }
    const exportId = this.message.loading('请求中..', { nzDuration: 0 }).messageId;
    const res = await (num ==0 ? this.services.incomeExportData(params) : this.services.expendExportData(params));
    this.message.remove(exportId);

    if (num == 0) {
      this.commonService.downLoadBlobFile(res, `爱豆收入统计`);
    } else {
      this.commonService.downLoadBlobFile(res, `爱豆支出统计`);
    }
  }
}
